import axios from 'axios'
import {router} from '../route-config'
import {AUTH_ERROR} from '../util/constant'

// export default axios.create({
//   timeout: 10 * 1000,
//   baseURL: '/api/music'
// })

function getAxiosInstance() {
  const instance = axios.create({
    timeout: 10 * 1000,
    baseURL: '/api/music',
    transformRequest: [function (data, headers) {
      //过滤穿出的值
      // console.log(data)
      return data;
    }],

    // `transformResponse` allows changes to the response data to be made before
    // it is passed to then/catch
    transformResponse: [function (data) {
      console.log(data)
      return data;
    }],

    // adapter: function (config) {
    //   console.log(config)
    //   return config
    // }

    auth: {
      username: 'user',
      password: 'PassWorld'
    },
    responseType: 'json', // default
    responseEncoding: 'utf8', // default
    onUploadProgress: function (progressEvent) {
      // Do whatever you want with the native progress event
    },
    onDownloadProgress: function (progressEvent) {
      // Do whatever you want with the native progress event
    },
    // `maxContentLength` defines the max size of the http response content in bytes allowed
    maxContentLength: 2000,
    validateStatus: function (status) {
      return status >= 200 && status < 300; // default
    },
    // `socketPath` defines a UNIX Socket to be used in node.js.
    // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
    // Only either `socketPath` or `proxy` can be specified.
    // If both are specified, `socketPath` is used.
    // socketPath: null, // default
    // `cancelToken` specifies a cancel token that can be used to cancel the request
    // (see Cancellation section below for details)
    // cancelToken: new CancelToken(function (cancel) {
    //   console.log('cancel')
    // })
  })

  instance.interceptors.request.use(function (config) {
    // console.log('config' + JSON.stringify(config))
    // console.log('count'+count++)
    const Token = 'Token'
    return {
      ...config,
      hearts: Object.assign({}, config.headers, {Authorization: Token})
    };
  }, function (error) {
    return Promise.reject(error);
  });

// 添加响应拦截器
  instance.interceptors.response.use(function (response) {
    // console.log('response' + JSON.stringify(response))
    if (response.status === AUTH_ERROR) {
      console.log('鉴权失败')
      router.replace('/login')
      // this.redirect('/login')
      // this.loction.replace('/login')
    } else {
      return response;
    }
  }, function (error) {
    return Promise.reject(error);
  });
  return instance
}

export default getAxiosInstance()
